package com.coffee.admin.service.supplier.impl;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.admin.api.common.service.SmsCodeService;
import com.coffee.admin.api.login.request.LoginByPasswordRequert;
import com.coffee.admin.api.login.request.LoginBySmsRequert;
import com.coffee.admin.api.supplier.query.SupplierQuery;
import com.coffee.admin.api.supplier.req.SupplierForgetPasswordReq;
import com.coffee.admin.api.supplier.req.SupplierUpdatePasswordReq;
import com.coffee.admin.api.supplier.result.SupplierResult;
import com.coffee.admin.api.supplier.service.SupplierLoginService;
import com.coffee.admin.api.supplier.service.SupplierService;
import com.coffee.admin.service.supplier.bean.Supplier;
import com.coffee.admin.service.supplier.dao.SupplierDao;
import com.coffee.core.constant.Status;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.enums.SmsSourceEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.exception.ValidateBusinessException;
import com.coffee.core.util.BeanUtils;
import com.coffee.core.util.PasswordUtil;
import com.coffee.core.util.RegexUtils;
import com.coffee.core.util.UUIDUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

@DubboService(dynamic = true)
public class SupplierLoginServiceImpl implements SupplierLoginService {
    private final static Logger logger = LoggerFactory.getLogger(SupplierLoginServiceImpl.class);

    @DubboReference
    private SupplierService supplierService;
    @DubboReference
    private RedisService redisService;
    @DubboReference
    private SmsCodeService smsCodeService;
    @Resource
    private SupplierDao supplierDao;

    public static void main(String[] args) {
        System.out.println(PasswordUtil.getPass("123456"));
        System.out.println("$2a$10$800023603127966391375upzzU8unIVtE51F3g0MPREkVQwID5cQi".length());
    }


    public void checkMobile(String mobile) throws BusinessException {
        ValidateBusinessException.assertStringNotBlank(mobile, ExceptionEnum.ERROR_1201);
        boolean isMobile = RegexUtils.checkMobile(mobile);
        ValidateBusinessException.assertTrue(isMobile, ExceptionEnum.ERROR_1218);
    }

    @Override
    public String passwordLogin(LoginByPasswordRequert req) throws BusinessException {
        //手机号码校验
        String mobile = req.getMobile();
        this.checkMobile(mobile);

        //密码校验
        String password = req.getPassword();
        ValidateBusinessException.assertStringNotBlank(password, ExceptionEnum.ERROR_1202);
        SupplierQuery param = new SupplierQuery();
        param.setMobile(req.getMobile());
        SupplierResult supplierResult = this.supplierService.getSupplierResult(param);

        if (supplierResult == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1233);
        }

        if (!PasswordUtil.checkPass(req.getPassword(), supplierResult.getPassword())) {
            throw BusinessException.build(ExceptionEnum.ERROR_1203);
        }
        String isEnable = supplierResult.getIsEnable();
        if ("N".equals(isEnable)) {
            throw BusinessException.build(ExceptionEnum.ERROR_1228);
        }
        //保存用户信息到redis中
        String token = setLoginUser(supplierResult);
        return token;
    }

    @Override
    public String smsLogin(LoginBySmsRequert req) throws BusinessException {
        //手机号码校验
        String mobile = req.getMobile();
        this.checkMobile(mobile);


        SupplierQuery param = new SupplierQuery();
        param.setMobile(req.getMobile());
        SupplierResult supplierResult = this.supplierService.getSupplierResult(param);

        if (supplierResult == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1233);
        }
        //校验验证码
        String smsCode = req.getSmsCode();
        boolean isValid = smsCodeService.validateSmsCode(mobile, smsCode, SmsSourceEnum.BACKSTAGE_LOGIN);
        if (!isValid) {
            throw BusinessException.build(ExceptionEnum.ERROR_1210);
        }

        String isEnable = supplierResult.getIsEnable();
        if ("N".equals(isEnable)) {
            throw BusinessException.build(ExceptionEnum.ERROR_1228);
        }
        //登录
        String token = setLoginUser(supplierResult);
        return token;
    }


    @Override
    public String forgetPassword(SupplierForgetPasswordReq req) throws BusinessException {
        //手机号码校验
        String mobile = req.getMobile();
        this.checkMobile(mobile);


        SupplierQuery param = new SupplierQuery();
        param.setMobile(req.getMobile());
        SupplierResult supplierResult = supplierService.getSupplierResult(param);

        if (supplierResult == null) {
            throw BusinessException.build(ExceptionEnum.ERROR_1233);
        }
        //校验验证码
        String smsCode = req.getSmsCode();
//        boolean isValid = smsCodeService.validateSmsCode(mobile, smsCode, SmsSourceEnum.SUPPLIER_FORGOTPASSWORD);
//        if (!isValid) {
//            throw BusinessException.build(ExceptionEnum.ERROR_1210);
//        }
        SupplierUpdatePasswordReq supplierUpdatePasswordReq = new SupplierUpdatePasswordReq();
        supplierUpdatePasswordReq.setId(supplierResult.getId());
        supplierUpdatePasswordReq.setNewPassword(req.getNewPassword());
        supplierService.updatePassword(supplierUpdatePasswordReq);
        //登录
        String token = setLoginUser(supplierResult);
        return token;
    }


    private String setLoginUser(SupplierResult supplierResult) {
        String token = "s-" + UUIDUtils.getUUID();
        LoginUser userBo = new LoginUser();
        Integer firstPid = getFirstPid(supplierResult);
        logger.info("supplierId==" + firstPid);
        userBo.setSupplierId(firstPid);
        userBo.setUserId(supplierResult.getId());
        userBo.setUserName(supplierResult.getName());
        userBo.setSupplierIsAdmin(supplierResult.getIsAdmin());
        redisService.set(token, JSONObject.toJSONString(userBo), Status.ExpireEnum.EXPIRED_TOKEN);
        return token;
    }

    Integer getFirstPid(SupplierResult supplierResult) {
        if (supplierResult.getPid() == 0) {
            Integer id = supplierResult.getId();
            return id;
        } else {
            SupplierResult supplierResult1 = new SupplierResult();
            Supplier supplier = supplierDao.findById(supplierResult.getPid());
            if (supplier == null) {
                return null;
            }
            BeanUtils.copyProperties(supplierResult1, supplier);
            return getFirstPid(supplierResult1);
        }

    }
}
